<script>
// 快手配置
let extConfig = require("./util/tempConfig.js");
// 抖音配置
let ttConfig = require("./util/ttConfigSet.js");
export default {
	globalData: {
		videoBack:false,
		zwyVideoDuration:{},
		extConfig:'',
		PROFILE: 'online', //online dev qa
		needDarenChoose:false,
		attributeServerApi:false,
		batchEnter: false,
		batchId: '',
		needRefresh: true,
		pathOptions: '',
		isLogining: false,
		shareBatchId: '',
		scene: '0',
		sceneCheck: false,
		loginFail: 0,
		zwyQueue: [], // getApp().globalData.zwyQueue
		loginTimer: '',
		loginTimes: 0,
		statisTimer: '',
		statisPostData: [],
		statisPostDataAd:[],
		adHasSee: 0,
		spreadChannelId: '',
		//#ifdef MP-KUAISHOU
		client: 'MP-KUAISHOU',
		//#endif
		//#ifdef MP-TOUTIAO
		client: 'MP-TOUTIAO',
		//#endif
		isIos: '',
		copyFirst: false,
		copyType: 3, // 1海洋短剧 2剧多多 3果果剧场
		nowTTClient: false, // 临时添加关注限制 海洋短剧和剧多多发: true 和果果剧场不发: false
		templateMessageTaskId: '', // 上报模板ID
		templateMessageTaskType: '', // 上报模板类型
		isConfigSsVip: false, // 是否配置了大会员档位
    	ssVipMessExpirationTime: '', // 大会员时间
		nowScene: '',
		backStage: false, // 是否进入后台
		chainId: '', // 投放链ID
		iosPaySwitch: false, // iOS支付开关,
		followedId:'2670056352',//快手服务号id
		seqEpisodeListSwitch: false, // 剧集跳集解锁开关
		popupMess: { // 批次进来的弹窗信息
			isClose: true, // 弹窗是否可关闭
			stickingPointSequence: 0, // 卡点集数
			dialogRate: 0, // 弹窗频率
			buySpace: 0, //付费集数
			buyType:'',// 付费前  1 付费后
			viewPopup: false,
			groupCombineId: '', //群组id
			addGroupStyle:''//加群样式
		},
		dyInsertMess:{
			diversionSceneType:'',//导流场景 支付前，支付后
			guideSequence:'', // 卡点集数
			dialogRate: 0, // 弹窗频率
			guideDialogSwitch: false, // 弹窗是否可关闭
			viewDyPopup:false,
			openId:'',
			douYinUserId:'' //抖音号
		},
		dyGroupMess:{
			diversionSceneType:'',//导流场景 支付前，支付后
			guideSequence:'', // 卡点集数
			dialogRate: 0, // 弹窗频率
			guideDialogSwitch: false, // 弹窗是否可关闭
			viewJqPopup:false,
			groupId: '', //群组id
		},
		addGroupFlag:false,
		spreadModeBatch: '',
		callBack:false,//判断是否广告用户用户隐藏推广按钮
		spreadMode:'',//判断是否广告用户用户隐藏推广按钮
		lastAdTimestamp:'',//插屏广告上一次曝光时间
		isViewOrganization: true, // 是否展示合作入口
		shareWithBatchId:false, // 分享携带批次号是否开启
		isEmpowerStatus:true,//是否调用私信授权
		isEmpowerStatusBtn:true,//是否调用私信授权播放页按钮
		isBusinessChain:false,
		adPlanParma: {
			promotionId: '', // 广告组ID
			aid: '', // 广告组id
			ksUnitId: '', // 快手组id
		},
		payAmountCloseSwitch:false, // 充值面板是否可关闭
		isOperateType:true,
		isAdComeCheck: false, // 查询是否从广告进入
 	},
	onLaunch: async function(e) {	
		console.log('App Launch', e);
		// 清除广告
		uni.removeStorageSync('indexAdViewMess')
		//#ifdef MP-KUAISHOU
			let accountInfoZwy = uni.getAccountInfoSync();
			if (accountInfoZwy && accountInfoZwy.miniProgram) accountInfoZwy = accountInfoZwy.miniProgram;
			this.globalData.extConfig = extConfig[accountInfoZwy.appId];
			uni.setStorageSync('clientId',this.globalData.extConfig['clientId']);
			uni.setStorageSync('appId',this.globalData.extConfig['appId']);
			uni.setStorageSync('appKey',this.globalData.extConfig['appKey']);

			// 快手广告计划的参数存储
			if(e && e.query.batchId) {
				this.globalData.adPlanParma.aid = e.query.aid || ''
				this.globalData.adPlanParma.ksUnitId = e.query.ksUnitId || ''
			}
		//#endif
		//#ifdef MP-TOUTIAO
			uni.onError((err) => {
				console.log('err------', err)
				this.errorPopup('', '', err, 1)
			})
			// 获取配置信息
			let ttAccountInfo = tt.getEnvInfoSync() && tt.getEnvInfoSync().microapp
			if(ttAccountInfo && ttAccountInfo.appId) {
				let ttConfigMess = ttConfig[ttAccountInfo.appId]
				this.ttConfigMess = ttConfigMess
				this.copyType = ttConfigMess.copyType
				this.nowTTClient = ttConfigMess.nowTTClient
			}

			// 抖音广告计划的参数存储
			if(e && e.query.batchId) {
				this.globalData.adPlanParma.promotionId  = e.query.promotion_id || e.query.promotionid || e.query.promotionId || ''
			}
		//#endif
		// 消息上报参数存储
		if(e.query && e.query.templateMessageTaskId) {
			let {
				templateMessageTaskId,
				templateMessageTaskType
			} = e.query
			this.globalData.templateMessageTaskId = templateMessageTaskId
			this.globalData.templateMessageTaskType = templateMessageTaskType
		}
		uni.setStorageSync('currentProfile',getApp().globalData['PROFILE']);
		if(uni.getStorageSync('PROFILE')) getApp().globalData['PROFILE'] = uni.getStorageSync('PROFILE');
		if(uni.getStorageSync('hasSetClip') && e.scene.indexOf('1013') != -1){
			if(uni.getStorageSync('userLockBtnClick')){
				//点击关注服务号锁后直接返回
				console.log('非口令进入');
				uni.setStorageSync('userLockBtnClick',false);
			}else{
				console.log('判断是口令进来的');
				// 判断是口令进来的 口令有批次号则设置此次的批次号为口令批次号
				if(!e.query.batchId && uni.getStorageSync('kuaiShouWatchwordBatchId')) {
					e.query.batchId = uni.getStorageSync('kuaiShouWatchwordBatchId');
					getApp().globalData.batchEnter = true;
					getApp().globalData.batchId = e.query.batchId;
				}
				
				let clipUrl = uni.getStorageSync('clipUrl');
				if(clipUrl.indexOf('kuaishou.com') != -1){
					// 口令进入服务号
					this.$uma && this.$uma.trackEvent('Ume_password', {
						name: 'Ume_password_enter_SN'
					});
				}else {
					// 口令进入小程序
					this.$uma && this.$uma.trackEvent('Ume_password', {
						name: 'Ume_password_enter_APP'
					});
				}
				uni.setStorageSync('hasSetClip',false);
			}
		}
		

		
		if (e && e.query.batchId) {
			this.globalData.batchId = e.query.batchId
			uni.setStorageSync('bufferBatchId', e.query.batchId)
			this.getSpreadChannelId(e.query.batchId);
			// await this.getAdMessStatus(e.query.batchId)
		}
		if (!e.query.useLastPath) uni.setStorageSync('enterPath', JSON.stringify(e));

		const updateManager = uni.getUpdateManager();

		updateManager.onUpdateReady(async () => {
			const { confirm } = await uni.showModal({
				title: '更新提示',
				content: '新版本已经准备好，是否重启应用？'
			});

			if (confirm) {
				updateManager.applyUpdate();
			}
		});
		// 判断是不是iphone X系列手机
		uni.getSystemInfo({
			success:res=> {
				const model = res.model;
				uni.setStorageSync('phoneModel', model);
				if (model.search('iPhone X') != -1) {
					this.globalData.isIpx = true;
				} else {
					this.globalData.isIpx = false;
				}
				if (model.search('iPhone') != -1 || model.search('iPad') != -1) {
					this.globalData.isIos = true;
				} else {
					this.globalData.isIos = false;
				}
				console.log('this.globalData.isIos', this.globalData.isIos);
				let { screenWidth, screenHeight } = res;
				let isLongScreen = Math.floor((screenWidth / screenHeight) * 100) / 100;
				if (isLongScreen < 0.5) {
					this.globalData.isLongScreen = true;
				} else if (isLongScreen > 0.55) {
					this.globalData.isShortScreen = true;
				} else {
					this.globalData.isLongScreen = false;
				}
				this.globalData.screenWidth = res.screenWidth;
				// bottom 安全区域
				if (res.safeArea && res.screenHeight > res.safeArea.bottom) {
					this.globalData.safeBottom = res.screenHeight - res.safeArea.bottom;
				}
			}
		});
		
		let accountInfo;
		//#ifdef MP-KUAISHOU
		accountInfo = await uni.getAccountInfoSync();
		if (accountInfo && accountInfo.miniProgram) accountInfo = accountInfo.miniProgram;
		//#endif
		//#ifdef MP-TOUTIAO
		if(tt.getEnvInfoSync) accountInfo = tt.getEnvInfoSync();
		if (accountInfo && accountInfo.microapp) accountInfo = accountInfo.microapp;
		
		//#endif
		uni.setStorageSync('appId', accountInfo.appId);


		setTimeout(() => {
			this.zwyRequest({
				url: "/cdp/launch",
				method: 'post'
			})
		}, 5000)
	},
	onShow: async function(e) {
		// 获取用户进入小程序的时间
		let inComeTimeLog = wx.getStorageSync('inComeTimeLog')
		if(!inComeTimeLog) {
			let startTimeIn = new Date().getTime()
			wx.setStorageSync('inComeTimeLog', startTimeIn)
		}
		
		this.globalData.backStage = false
		if (e && e.query.batchId) {
			this.getOrganizationInfo(e.query.batchId)
			this.getSpreadChannelId(e.query.batchId)

			if (!e.query.useLastPath) uni.setStorageSync('enterPath', JSON.stringify(e));
		}
		//#ifdef MP-TOUTIAO
			this.globalData.nowScene = e.scene
			if(e.scene == '025001'){
				this.globalData.isAdComeCheck = true
			}
			// 检查当前用户是否是会员
			this.getMemberTt(this)
			// 检查大会员开启状态
			if (e && e.query.batchId) {
				this.getMemberConfig(e.query.batchId);
			}
			let ttAccountInfo = tt.getEnvInfoSync() && tt.getEnvInfoSync().microapp
			if(ttAccountInfo && ttAccountInfo.appId) {
				let ttConfigMess = ttConfig[ttAccountInfo.appId]
				this.copyType = ttConfigMess.copyType
				this.nowTTClient = ttConfigMess.nowTTClient
				uni.setStorageSync('ttConfigMess', ttConfigMess)
			}
		//#endif
		//#ifdef MP-KUAISHOU
			// 检查当前用户是否是会员
			this.getMemberTt(this)
			// 检查大会员开启状态
			if (e && e.query.batchId) {
				this.getMemberConfig(e.query.batchId);
			}
		//#endif
		if (e.scene != this.globalData.scene) {
			this.globalData.needRefresh = true;
		}
		let tempScene = String(e.scene);
		this.globalData.scene = e.scene;
		
		//#ifdef MP-KUAISHOU
		if (tempScene.indexOf('1013') != -1 || tempScene.indexOf('1040') != -1) {
			this.globalData.sceneCheck = true;
		} else {
			this.globalData.sceneCheck = false;
		}
		//#endif
	},
	onHide: function() {
		console.log('App Hide');
		// 获取用户进入小程序的时间
		let inComeTimeLog = wx.getStorageSync('inComeTimeLog')
		if(inComeTimeLog) {
			let endTimeIn = new Date().getTime()
			this.inComeTimeReport({
				startTime: inComeTimeLog,
				endTime: endTimeIn
			})
			wx.removeStorageSync('inComeTimeLog')
		}

		this.globalData.backStage = true
		uni.removeStorageSync('phoneFlag');
		uni.removeStorageSync('showSafeguard');
		uni.removeStorageSync('showLogin');
		uni.removeStorageSync('addGroup')
	},
	methods: {
		// 上报用户停留客户端时长
		inComeTimeReport(data) {
			this.zwyRequest({
					method: 'post',
					url: "/client_dwell_time",
					isReport: true,
					data
			})
    },
		async getOrganizationInfo(batchId) {
			let res = await this.zwyRequest({
				method: 'get',
				url: `/cdp/launch/organization_info?batchId=${batchId}`
			})
			if(res && res.organizationType) {
				if(['CPS_BUSINESS_DISTRIBUTOR'].includes(res.organizationType)) {
					this.globalData.isViewOrganization = false
				} else {
					this.globalData.isViewOrganization = true
				}
				
			} else {
				this.globalData.isViewOrganization = true
			}
			console.log('122112----', res)
		},
		// 检查当前是否是大会员切是否在有效期内
		checkMemberSsVip: function () {
			let memberInfoSsVip = wx.getStorageSync('memberInfoSsVip')
			console.log('memberInfoSsVip--------------------', memberInfoSsVip)
			// if (!memberInfoSsVip && !memberInfo.memberInfoSsVip) return false
			if (!memberInfoSsVip && !memberInfoSsVip.memberInfoSsVip) return false
			let nowTime = (new Date()).getTime();
			if (memberInfoSsVip.expirationTime - nowTime >= 0) return true
			else return false
		},
		// 获取会员充值档位
		async getMemberMess(_this, packageId) {
			try {
				if(!packageId) {
					uni.showToast({
						title: '无充值信息配置',
						icon: 'none'
					})
				}
				let res = await _this.zwyRequest({
					method: 'get',
					url: '/wealth/api/pay_client_setting/membership_fee_setting',
					header: {
						'content-type': 'application/json;charset=utf-8',
						"isBiz": true
					},
					data: {
						payUseId: packageId
					}
				})
				console.log(res)
				return res
			} catch (error) {
				console.log(error)
			}
		},
		// 提交充值大会员订单
		async subMemberOrder(_this, obj) {
			try {
				// 回传上报
				//#ifdef MP-KUAISHOU
				_this.postActive('order')
				//#endif
				let header = {
					'content-type': 'application/json;charset=utf-8'
				}
				if(obj.iosPayVersion) {
					header['ios-pay-version'] = true
				} else {
					header['ios-pay-version'] = false
				}
				let res = await _this.zwyRequest({
					url: '/wealth/api/pay_client/top_up_preorder',
					method: 'post',
					header: header,
					data: {
						moneyFen: obj.moneyFen,
						payUse: 'FOR_MEMBERSHIP',
						useId: obj.packageId
					}
				})

				return res
			} catch (error) {
				console.log(error)
			}
		},
		// 微信充值弹窗
		ttPaySub(orderInfo) {
			return new Promise((resolve, reject) => {
				uni.pay({
					service: 5,
					orderInfo: orderInfo,
					success: (res) => {
						resolve(res)
					},
					fail: (res) => {
						reject(res)
					}
				})
			})   
		},
		// 快手充值
		ksPaySub(orderInfo) {
			console.log('orderInfo---------', orderInfo)
			return new Promise((resolve, reject) => {
				ks.pay({
					serviceId: '1',
					orderInfo: orderInfo,
					success: (res) => {
						resolve(res)
					},
					fail: (res) => {
						reject(res)
					}
				})
			})   
		},
		// 充值成功上报
		async czSucc(_this, orderId) {
			try {
				let res = await _this.zwyRequest({
					header: {
						'content-type': 'application/x-www-form-urlencoded;charset=UTF-8'
					},
					method: 'post',
					url: `/wealth/api/pay_order/done?orderId=${orderId}`,
					data: { orderId: orderId }
				})

				if (res && res.payStatus == 'BE_READY') {
					uni.showToast({
						title: '充值成功',
						icon: 'none'
					})
					//#ifdef MP-TOUTIAO
					tt.showFavoriteGuide({
						type: "bar",
						content: "一键添加到「我的小程序」",
						position: "bottom",
						success(res) {
							console.log("引导组件展示成功", res);
						},
						fail(err) {
							console.log("引导组件展示失败", err);
						},
					});
					//#endif
					return res
				}
			} catch (error) {
				console.log(error)
			}
		},
		// 获取会员状态
		async getMemberTt(_this) {
			try {
				let res = await _this.zwyRequest({
					method: 'get',
					url: '/cdp/user/membership',
				})
				// 大会员信息状态存储
				let obj = res.find(item => item.membershipType === 2)
				if (obj) {
					uni.setStorageSync('memberInfoSsVip', obj)
					getApp().globalData.ssVipMessExpirationTime = obj.expirationTime
				} else {
					uni.removeStorageSync('memberInfoSsVip')
				}
				return res
			} catch (error) {
				console.log(error)
			}
		},
		/**
		 * 获取充值配置
		 * 存储大会员配置状态
		 */
    	async getMemberConfig(batchId) {
			try {
				await this.getChannelId(batchId)
				await this.getChannelInfo(batchId)
				let time = Math.random()
				let res = await this.zwyRequest({
					method: 'get',
					url: `/wealth/api/pay_setting/global_vip_open?number=${time}`
				})
				if(res) {
					let status = res.data
					getApp().globalData.isConfigSsVip = status || false
				}
			} catch (error) {
				console.log(error)
			}
		},
		// 保存渠道信息
		async getChannelId(batchId) {
			try {
				let res = await this.zwyRequest({
					method: 'get',
					url: '/cdp/launch/spread_info',
					data: {
						batchId: batchId
					}
				})
				if (res && res.spreadChannel && res.spreadChannel.enableSubscribeGuide) {
					getApp().globalData.spreadChannelId = res.spreadChannel['id']
				}
				// 添加投放链ID
				if(res && res.spreadBatch && res.spreadBatch.chainId) {
					getApp().globalData.chainId = res.spreadBatch.chainId
				}
			} catch (error) {
				console.log(error)
			}
		},

		// 保存一键加群卡点信息
		async getChannelInfo(batchId) {
			try {
				let res = await this.zwyRequest({
					method: 'get',
					url: '/cdp/launch/getMediaSpreadInfo',
					data: {
						batchId: batchId
					}
				}) 
				// 卡点信息
				if(res.mediaAccountSpreadBatchDTO && res.mediaAccountSpreadBatchDTO.mediaAccountAppId && res.mediaAccountSpreadBatchDTO.spreadBatchExt.guideType && res.mediaAccountSpreadBatchDTO.spreadBatchExt.guideDialogSwitch){
					this.globalData.dyInsertMess.viewDyPopup = true
					this.globalData.dyInsertMess.diversionSceneType = res.mediaAccountSpreadBatchDTO.spreadBatchExt.guideType //导流场景 1支付前，2支付后
					this.globalData.dyInsertMess.guideSequence = res.mediaAccountSpreadBatchDTO.stickingPointSequence + 1// 卡点集数
					this.globalData.dyInsertMess.dialogRate = res.mediaAccountSpreadBatchDTO.dialogRate// 弹窗频率
					this.globalData.dyInsertMess.guideDialogSwitch = res.mediaAccountSpreadBatchDTO.spreadBatchExt.guideDialogSwitch === 1 ? false : true// 弹窗是否可关闭 1不可关闭 2可关闭
					this.globalData.dyInsertMess.openId = res.mediaAccountSpreadBatchDTO.douYinOpenId  //openid
					this.globalData.dyInsertMess.douYinUserId = res.mediaAccountSpreadBatchDTO.mediaAccountAppId //抖音号
					this.globalData.isOperateType = false

				}else{
					this.globalData.isOperateType = true
				}
				// if(res.mediaAccountSpreadBatchDTO && res.mediaAccountSpreadBatchDTO.spreadBatchExt.guideType && res.mediaAccountSpreadBatchDTO.spreadBatchExt.guideDialogSwitch) {
				// 	this.globalData.popupMess.viewPopup = true
				// 	this.globalData.popupMess.isClose = res.mediaAccountSpreadBatchDTO.spreadBatchExt.guideDialogSwitch === 1 ? false : true
				// 	this.globalData.popupMess.buyType = res.mediaAccountSpreadBatchDTO.spreadBatchExt.guideType === 2 ? 1 : 0
				// 	this.globalData.popupMess.dialogRate = res.mediaAccountSpreadBatchDTO.dialogRate
				// 	this.globalData.popupMess.stickingPointSequence = res.mediaAccountSpreadBatchDTO.stickingPointSequence + 1
				// 	this.globalData.popupMess.groupCombineId = res.mediaAccountSpreadBatchDTO.spreadBatchExt.groupCombineId
				// 	this.globalData.popupMess.addGroupStyle = res.mediaAccountSpreadBatchDTO.spreadBatchExt.addGroupStyle
				// 	this.globalData.popupMess.buySpace = res.mediaAccountSpreadBatchDTO.buySpace
				// 	this.globalData.isOperateType = false
				// } else {
				// 	this.globalData.popupMess.viewPopup = false
				// }
				console.log(this.globalData.dyInsertMess,'===================================================');

			} catch (error) {
				console.log(error)
			}
		},
		getSpreadChannelId(batchId) {
			this.zwyRequest({
				method: 'get',
				url: '/cdp/launch/spread_info',
				data: {
					batchId: batchId
				}
			}).then(res => {
				// 添加投放链ID
				if(res && res.spreadBatch && res.spreadBatch.chainId) {
					getApp().globalData.chainId = res.spreadBatch.chainId
				}
				if (res.spreadBatch && res.spreadBatch['spreadChannelId'] !== getApp().globalData.spreadChannelId) {
					getApp().globalData.spreadChannelId = res.spreadBatch['spreadChannelId'];
				}
				if(res.spreadBatch && (res.spreadBatch['spreadMode'] == 'IAA_AD_LOCK_DOUYIN' || res.spreadBatch['spreadMode'] == 'SHORT_THEATER_PROMOTION_TIKTOK' || res.spreadBatch['spreadMode'] == 'ACTIVE_DOUYIN')){
					getApp().globalData.shareWithBatchId = true
				}
				if (res && res.spreadBatch && res.spreadBatch.spreadMode) {
					getApp().globalData.spreadMode = res.spreadBatch.spreadMode
				}
				//#ifdef MP-KUAISHOU
				if (res.spreadBatch && res.spreadBatch.watchword && res.spreadBatch.watchword != undefined && res.spreadBatch.watchword != 'undefined'  && uni.setClipboardData) {
					uni.setStorageSync('watchword',res.spreadBatch.watchword);
					if(res.spreadBatch.kuaiShouWatchwordBatchId) uni.setStorageSync('kuaiShouWatchwordBatchId',res.spreadBatch.kuaiShouWatchwordBatchId);
					console.log('setWatchWord144',res.spreadBatch.watchword);
					console.log('口令曝光');
					this.$uma && this.$uma.trackEvent('Ume_password', {
						name: 'Ume_password_PV'
					});
				} else {
					// 无口令清除前面的批次口令和信息
					uni.removeStorageSync('watchword')
					uni.removeStorageSync('kuaiShouWatchwordBatchId')
				}
				//#endif
			});
		},

	}
};
</script>

<style>
@import './common/oneClass.css';
/* color-ui库 */
@import "colorui/main.css";
@import "colorui/icon.css";
@import "colorui/animation.css";
@keyframes breathe {
	0%,
	40%,
	80%,
	100% {
		transform: scale(1);
	}
	20%,
	60% {
		transform: scale(1.05);
	}
}

.clamp {
	display: -webkit-box;
	word-break: break-all;
	-webkit-box-orient: vertical;
	-webkit-line-clamp: 1;
	overflow: hidden;
	text-overflow: ellipsis;
}

.breathe {
	animation: breathe 1.1s ease-in-out infinite;
}

@import './common/oneClass.css';
/*每个页面公共css */
/*每个页面公共css */
.container999 {
	width: 100vw;
	min-height: 100vh;
}
::-webkit-scrollbar {
	width: 0;
	height: 0;
	color: transparent;
}
</style>
